package high.concurrent.esserver.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import high.concurrent.constant.SqlType;
import high.concurrent.esmodel.ProductOrder;
import high.concurrent.esserver.EsServer;
import high.concurrent.utils.ObjectToMap;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.beans.IntrospectionException;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;

@Service
public class EsServerImpl implements EsServer {

    @Autowired
    private RestHighLevelClient client;

    /**
     * 监听到的数据对ES操作
     * @param data  数据
     * @param index 索引值，相当于库
     * @param aclass  要转的类型
     * @return
     */
    @Override
    public boolean operateEs(JSONObject data, String index, Class aclass) {

        // 类型， INSERT, UPDATE, DETAIL
        String type = (String) data.get("type");

        // 数据
        JSONArray jsonArray = (JSONArray) data.get("data");

        // 表名
        String tableName = (String) data.get("table");

        // 库名
        String databaseName = (String) data.get("database");

        boolean result = false;

        if(SqlType.INSERT.name().equals(type)){
            // 添加
            result = this.addEs(jsonArray, index, aclass, tableName, databaseName);

        }else if(SqlType.UPDATE.name().equals(type)){
            // 修改
            result = this.updateEs(jsonArray, index, aclass);

        }else if(SqlType.DELETE.name().equals(type)){
            // 删除
            this.deleteEs(jsonArray, index);
        }else{
            result = true;
        }
        return result;
    }

    /**
     * 添加数据到es
     * @param jsonArray  要存储得对象
     * @param index 索引值，相当于库
     * @param aclass 要转成的类型
     * @param tableName 表名
     * @param databaseName 库名
     * @return
     */
    private boolean addEs(JSONArray jsonArray, String index, Class aclass, String tableName, String databaseName){

        for(int i = 0; i < jsonArray.size(); i++){
            IndexResponse response = null;
            try {
                // 转成JSONObject，获取id，是数据的id，也是es的自身id
                JSONObject data = (JSONObject) JSONObject.toJSON(jsonArray.get(i));
                data.put("tableName", tableName);
                data.put("databaseName", databaseName);

                // 转成对象
                Object item = JSONObject.parseObject(data.toJSONString(), aclass);
                // id是es自己的id，不是我们的id
                IndexRequest request = new IndexRequest(index).id((String) data.get("id")).source(ObjectToMap.objectExchangeMap(item));
                response = client.index(request, RequestOptions.DEFAULT);
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.err.println(JSONObject.toJSON(response));
        }

        return true;
    }

    /**
     * 修改es，根据es自身id
     * @param jsonArray  要存储得对象
     * @param index 索引值，相当于库
     * @param aclass 要转成的类型
     * @return
     */
    public boolean updateEs(JSONArray jsonArray, String index, Class aclass) {

        for(int i = 0; i < jsonArray.size(); i++){
            UpdateResponse update = null;
            try {
                // 转成JSONObject，获取id，是数据的id，也是es的自身id
                JSONObject data = (JSONObject) JSONObject.toJSON(jsonArray.get(i));
                // 转成对象
                Object item = JSONObject.parseObject(data.toJSONString(), aclass);
                // id是es自己的id，不是我们的id
                UpdateRequest updateRequest = new UpdateRequest(index, (String) data.get("id")).doc(ObjectToMap.objectExchangeMap(item));
                update = client.update(updateRequest, RequestOptions.DEFAULT);
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.err.println(JSONObject.toJSON(update));
        }

        return true;
    }


    /**
     * 根据es自身id删除数据
     * @param jsonArray  要存储得对象
     * @param index 索引值，相当于库
     * @return
     */
    public boolean deleteEs(JSONArray jsonArray, String index) {

        for(int i = 0; i < jsonArray.size(); i++){
            DeleteResponse delete = null;
            try {
                // 转成JSONObject，获取id，是数据的id，也是es的自身id
                JSONObject data = (JSONObject) JSONObject.toJSON(jsonArray.get(i));
                // id是es自己的id，不是我们的id
                DeleteRequest deleteRequest = new DeleteRequest(index, (String) data.get("id"));
                delete = client.delete(deleteRequest, RequestOptions.DEFAULT);
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.err.println(JSONObject.toJSON(delete));
        }

        return true;
    }
}
